<template>
  <div class="table-indexes">
    <div class="indexes-table">
      <je-table
        ref="xTable"
        border
        stripe
        show-overflow="ellipsis"
        height="100%"
        resizable
        auto-resize
        :cell-style="cellStyle"
        keep-source
        show-header-overflow
        :row-config="{ isCurrent: true, isHover: true }"
        :data="tableIndexesdata.tableData"
        :loading="tableIndexesdata.loading"
        header-align="center"
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          showStatus: true,
        }"
      >
        <je-column type="checkbox" width="40" align="center"></je-column>
        <je-column type="seq" title="NO." width="50" align="center"></je-column>
        <je-column
          field="TABLEINDEX_ISCREATE"
          :title="$t('tableIndexesView.createColumn')"
          width="50"
          align="center"
        >
          <template #default="{ row }">
            {{ row.TABLEINDEX_ISCREATE == '1' ? '是' : '否' }}
          </template>
        </je-column>
        <je-column
          field="TABLEINDEX_NAME"
          :title="$t('tableIndexesView.indexNameColumn')"
          width="260"
        >
          <template #default="{ row }">
            <span v-html="formatSearchData(row.TABLEINDEX_NAME)"> </span>
          </template>
        </je-column>
        <je-column
          field="TABLEINDEX_FIELDNAME"
          :title="$t('tableIndexesView.filedNameColumn')"
          :edit-render="inputRender"
          width="220"
        >
          <template #edit="{ row }">
            <je-grid-select
              v-model:value="row.TABLEINDEX_FIELDNAME"
              :disabled="row.TABLEINDEX_ISCREATE == '1'"
              :select-options="{ title: '选择字段' }"
              name="TABLEINDEX_FIELDNAME"
              config-info="JE_CORE_TABLECOLUMN,TABLEINDEX_FIELDNAME~TABLEINDEX_FIELDCODE,TABLECOLUMN_NAME~TABLECOLUMN_CODE,S"
              :orders="[
                { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
                { code: 'SY_ORDERINDEX', type: 'ASC' },
              ]"
              :querys="getJQuery(row)"
            />
          </template>
          <template #default="{ row }">
            <span v-html="formatSearchData(row.TABLEINDEX_FIELDNAME)"> </span>
          </template>
        </je-column>
        <je-column
          field="TABLEINDEX_UNIQUE"
          :title="$t('tableIndexesView.soleColumn')"
          :edit-render="{}"
          width="80"
          align="center"
        >
          <template #edit="{ row }">
            <je-select
              v-model:value="row.TABLEINDEX_UNIQUE"
              style="width: 100%"
              :disabled="row.TABLEINDEX_ISCREATE == '1'"
            >
              <je-select-option
                v-for="item in tableIndexesdata.yesNoOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </je-select-option>
            </je-select>
          </template>
          <template #default="{ row }">
            {{ getSelectLabel(row.TABLEINDEX_UNIQUE, tableIndexesdata.yesNoOptions) }}
          </template>
        </je-column>
        <je-column
          field="TABLEINDEX_CLASSIFY"
          :title="$t('tableIndexesView.classifyColumn')"
          width="80"
          align="center"
        >
          <template #default="{ row }">
            {{ row.TABLEINDEX_CLASSIFY == 'PRO' ? '业务' : '系统' }}
          </template>
        </je-column>
        <je-column
          field="SY_ORDERINDEX"
          :title="$t('tableIndexesView.orderColumn')"
          width="80"
          :edit-render="numberRender"
          align="center"
        >
          <template #edit="{ row }">
            <je-input-number v-model:value="row.SY_ORDERINDEX" :min="0" />
          </template>
        </je-column>
        <je-column
          field="TABLEINDEX_REMARK"
          :title="$t('tableIndexesView.remarkColumn')"
          :edit-render="inputRender"
          min-width="220"
        >
          <template #edit="{ row }">
            <je-input v-model:value="row.TABLEINDEX_REMARK" />
          </template>
        </je-column>
        <template #pager>
          <je-pager
            v-model:current-page="tablePage.currentPage"
            v-model:page-size="tablePage.pageSize"
            :page-sizes="tablePage.pageSizes"
            align="left"
            style="height: 40px; padding: 0 10px"
            background
            :size="size"
            :total="tablePage.totalResult"
            :layouts="['JumpNumber', 'Sizes', 'FullJump', 'Total', 'Refresh']"
            @load="onPageChange"
          />
        </template>
        <template #tbar>
          <je-toolbar style="border-top: 1px solid #e6e6e6">
            <je-button type="text" @click="addIndexes">
              <template #icon><i class="fal fa-plus-circle"></i></template>{{ $t('btnAddText') }}
            </je-button>
            <je-button type="text" @click="deleteIndexes">
              <template #icon><i class="fal fa-times"></i></template>{{ $t('btnDeleteText') }}
            </je-button>
            <je-button type="text" @click="saveIndexes">
              <template #icon><i class="fal fa-save"></i></template>{{ $t('btnSaveText') }}
            </je-button>
            <TbFill />
            <je-input-search
              v-model:value="searchValue"
              :placeholder="$t('searchText')"
              style="width: 280px"
              :allow-clear="allowclear"
              :enter-button="$t('searchText')"
              @search="queryIndexes"
            >
              <template #prefix> <i class="fal fa-search" /> </template>
            </je-input-search>
          </je-toolbar>
        </template>
      </je-table>
    </div>
  </div>
</template>
<script>
  import { defineComponent, ref, onMounted, reactive, watch } from 'vue';
  import {
    Button,
    Grid,
    Input,
    Select,
    InputNumber,
    Modal,
    Pager,
    InputSelect,
    Toolbar,
  } from '@jecloud/ui';
  import { isNotEmpty } from '@jecloud/utils';
  import {
    getTableIndexData,
    addTableIndex,
    deleteTableIndex,
    updateTableIndex,
  } from '../../api/index';
  import { inputRender, numberRender } from '../../helper/edit-render';
  import { JE_TABLECLOUMN_SELECTOPTIONS, JE_TABLE_PAGESIZES } from '@/helper/common';

  export default defineComponent({
    name: 'TableIndexes',
    components: {
      JeButton: Button,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeInputSearch: Input.Search,
      JeInput: Input,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeInputNumber: InputNumber,
      JePager: Pager,
      JeGridSelect: InputSelect.Grid,
      JeToolbar: Toolbar,
      TbFill: Toolbar.Fill,
    },
    props: {
      tabKey: {
        type: String,
        default: '',
      },
      tableInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      refreshIndex: {
        type: Boolean,
        default: true,
      },
      productData: {
        type: Object,
        required: true,
        default: () => {
          return {};
        },
      },
    },
    emits: ['refreshHistory'],
    setup(props, { emit }) {
      const xTable = ref(null);
      const tabKey = ref(props.tabKey);
      const tableData = ref(props.tableInfo);
      const searchValue = ref('');
      const tableIndexesdata = reactive({
        tableData: [],
        yesNoOptions: JE_TABLECLOUMN_SELECTOPTIONS.isNullOptions,
        loading: true,
      });
      const tablePage = reactive({
        currentPage: 1,
        pageSize: 30,
        pageSizes: JE_TABLE_PAGESIZES,
        totalResult: 30,
      });
      // 关键字搜索标识
      const keywordQuery = ref(false);

      //分页条切换页数
      const onPageChange = () => {
        getIndexesData('page');
      };
      watch(
        () => props.refreshIndex,
        () => {
          getIndexesData();
        },
      );

      //获得表格数据
      const getIndexesData = (type) => {
        if (type == 'page') {
          tableIndexesdata.loading = true;
        }
        const j_query = {
          custom: [{ type: '=', code: 'TABLEINDEX_RESOURCETABLE_ID', value: tabKey.value }],
          order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
        };
        //搜索框搜索参数拼接
        if (type == 'query' && isNotEmpty(searchValue.value)) {
          j_query.custom.push({
            type: 'and',
            value: [
              {
                type: 'like',
                code: 'TABLEINDEX_NAME',
                value: searchValue.value.trim() || '',
                cn: 'or',
              },
              {
                type: 'like',
                code: 'TABLEINDEX_FIELDNAME',
                value: searchValue.value.trim() || '',
                cn: 'or',
              },
            ],
          });
          keywordQuery.value = true;
        } else {
          keywordQuery.value = false;
        }
        const params = {
          tableCode: 'JE_CORE_TABLEINDEX',
          j_query: JSON.stringify(j_query),
          page: tablePage.currentPage,
          start: (tablePage.currentPage - 1) * tablePage.pageSize,
          limit: tablePage.pageSize,
        };
        getTableIndexData(params)
          .then((data) => {
            if (type && searchValue.value) {
              searchType.value = true;
            }
            tableIndexesdata.tableData = data.rows;
            tablePage.totalResult = data.totalCount;
            tableIndexesdata.loading = false;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      onMounted(() => {
        getIndexesData();
      });

      //搜索框回车查询
      const queryIndexes = (e) => {
        searchType.value = false;
        getIndexesData('query');
      };

      watch(
        () => searchValue.value,
        (newVal) => {
          if (!newVal) {
            searchType.value = false;
          }
        },
      );

      //添加操作
      const addIndexes = () => {
        const $table = getXTable();
        const params = {
          JE_CORE_RESOURCETABLE_ID: tableData.value.JE_CORE_RESOURCETABLE_ID,
          SY_ORDERINDEX: tableIndexesdata.tableData.length,
        };
        addTableIndex(params)
          .then(async (data) => {
            //getIndexesData();
            const { row: newRow } = await $table.insert(data.data);
            await $table.setActiveCell(newRow, 'TABLEINDEX_FIELDNAME');
            Modal.notice(data.message, 'success');
            tablePage.totalResult++;
            emit('refreshHistory');
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //删除操作
      const deleteIndexes = () => {
        const $table = getXTable();
        const checkboxRecords = $table.getCheckboxRecords();
        if (checkboxRecords.length <= 0) {
          return Modal.alert('请选择要删除的数据！', 'warning');
        }
        Modal.confirm('是否删除数据?', () => {
          const ids = [];
          checkboxRecords.forEach((record) => {
            ids.push(record.JE_CORE_TABLEINDEX_ID);
          });
          if (ids.length <= 0) {
            return;
          }
          deleteTableIndex(
            {
              tableIndexIds: ids.join(','),
            },
            { pd: props.productData.productCode },
          )
            .then((data) => {
              Modal.notice(data.message, 'success');
              //getIndexesData();
              $table.remove(checkboxRecords);
              tablePage.totalResult = tablePage.totalResult - checkboxRecords.length;
              emit('refreshHistory');
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        });
      };

      //保存操作
      const saveIndexes = () => {
        const $table = getXTable();
        const insertRecords = $table.getInsertRecords();
        let updateRecords = $table.getUpdateRecords();
        updateRecords = updateRecords.concat(insertRecords);
        if (updateRecords && updateRecords.length > 0) {
          updateTableIndex({
            strData: JSON.stringify(updateRecords),
          })
            .then((data) => {
              Modal.notice(data.message, 'success');
              // 进行关键字搜索刷新数据
              if (isNotEmpty(searchValue.value) && keywordQuery.value) {
                getIndexesData('query');
              } else {
                getIndexesData();
              }
              emit('refreshHistory');
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        } else {
          Modal.notice('无数据操作!', 'info');
        }
      };

      // 列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };

      //根据条件改变单元格的样式
      const cellStyle = ({ row, column }) => {
        switch (column.property) {
          case 'TABLEINDEX_UNIQUE': // 唯一列
            return { backgroundColor: row.TABLEINDEX_UNIQUE == '1' ? '#e0ffeb' : '#faf9da' };
          case 'TABLEINDEX_ISCREATE': // 创建列
            return { backgroundColor: row.TABLEINDEX_ISCREATE == '1' ? '#e0ffeb' : '#faf9da' };
          case 'TABLEINDEX_CLASSIFY': // 分类列
            return {
              backgroundColor: row.TABLEINDEX_CLASSIFY == 'PRO' ? 'rgb(251 198 198)' : '#B5E9FD',
            };
        }
      };

      //获得列表对象
      const getXTable = () => {
        return xTable.value.$plugin;
      };

      const searchType = ref(false);
      const formatSearchData = (name) => {
        let text = name;
        if (name && name != undefined && searchValue.value.length > 0 && searchType.value) {
          var re = new RegExp(searchValue.value, 'g');
          let replaceString = '<span style="color:red;">' + searchValue.value + '</span>';
          text = name.replace(re, replaceString);
        }
        return text;
      };

      //分装j_query
      const getJQuery = (row) => {
        let j_query = [
          {
            code: 'TABLECOLUMN_RESOURCETABLE_ID',
            type: '=',
            value: row.TABLEINDEX_RESOURCETABLE_ID,
            cn: 'and',
          },
        ];
        return j_query;
      };

      return {
        addIndexes,
        deleteIndexes,
        saveIndexes,
        tableIndexesdata,
        searchValue,
        queryIndexes,
        getSelectLabel,
        cellStyle,
        getXTable,
        xTable,
        tableData,
        tablePage,
        onPageChange,
        allowclear: true,
        lauoutOptions: { top: { size: 40 } },
        inputRender,
        numberRender,
        formatSearchData,
        searchType,
        getJQuery,
      };
    },
  });
</script>
<style lang="less" scoped>
  .table-indexes {
    height: 100%;
    .indexestop-button {
      display: flex;
      border-top: 1px solid #e6e6e6;
      justify-content: space-between;
      height: 40px;
      line-height: 39px;
      padding-right: 16px;
      padding-left: 4px;
    }
    .indexes-table {
      height: 100%;
    }
  }
</style>
<style lang="less">
  .table-indexes {
    .indexes-table {
      .vxe-table--render-default .vxe-table--border-line {
        border-left: 0 !important;
        border-right: 0 !important;
      }
    }
    .ant-input-search {
      border-bottom-right-radius: 0;
      border-top-right-radius: 0;
    }
    .ant-input-search.ant-input-affix-wrapper:hover {
      border: 1px solid #5c8dff !important;
      box-shadow: none !important;
    }
    .ant-input-search.ant-input-affix-wrapper-focused {
      border: 1px solid #5c8dff !important;
      box-shadow: none !important;
    }
    .ant-input-search-button {
      width: 60px;
    }
  }
</style>
